package com.example.dl645.config;

import com.example.dl645.util.SpringContextUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 应用启动后初始化Netty服务
 */
@Component
public class NettyServerRunner implements ApplicationRunner {

    @Autowired
    private ServerBootstrap serverBootstrap;

    @Autowired
    private NettyServerConfig nettyServerConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ConcentratorServerHandler handler = SpringContextUtil.getBean(ConcentratorServerHandler.class);

                ch.pipeline()
//                        .addLast(new IdleStateHandler(30, 30, 0, TimeUnit.SECONDS)) // 空闲检测
                        .addLast(new ByteArrayDecoder())
                        .addLast(new ByteArrayEncoder())
                        .addLast(handler);
            }
        });

        // 启动Netty服务
        int port = nettyServerConfig.getServerPort();
        ChannelFuture future = serverBootstrap.bind(port).sync();
        if (future.isSuccess()) {
            System.out.println("✅ Netty服务端启动成功，监听端口：" + port);
        } else {
            System.err.println("❌ Netty服务端启动失败，端口：" + port);
            throw new RuntimeException("Netty server start failed on port: " + port);
        }
    }
}